package com.ibl.rover.lite.client.Activity;

import android.app.ListActivity;
import java.util.ArrayList;
import java.util.List;
import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Application.OrderBookingLine;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.common.bean.ProductBean;
import com.ibl.rover.lite.common.bean.ProductCategroy;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.Criteria.Operators;
import com.ibl.rover.lite.common.db.DatabaseManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SearchProductListActivity extends ListActivity {

	private Logger logger = new Logger();
	private ApplicationContext roverApp;
	private DatabaseManager manager = null;
	private List<ProductBean> productBeans;
	private ProductCategroy productCategroy;
	private OrderBookingLine orderBookingLine;
	private ProgressDialog progressDlg = null;
	private Handler handler = new Handler();
	private ListView myList;
	private MyAdapter myAdapter;
	private ArrayList<Item> productitem = new ArrayList<Item>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			// setContentView(R.layout.search_product_list);

			initialize();
		} catch (Exception e) {
			logger.logException("onCreate Exceotion", e);
		}
	}

	/**
	 * Initialize Resources
	 */
	private void initialize() {
		try {

			roverApp = (ApplicationContext) getApplication();
			manager = roverApp.getDatabaseManager();

			productCategroy = (ProductCategroy) roverApp.getViewContext().get(
					RoverConstants.CURRENT_SELECTED_SKU);
			orderBookingLine = (OrderBookingLine) roverApp.getViewContext()
					.get(RoverConstants.CURRENT_ORDER_BOOKING_LINE);

			if (orderBookingLine.getProductBeanList() == null) {
				orderBookingLine
						.setProductBeanList(new ArrayList<ProductBean>());
				orderBookingLine
						.setProductQuantitylist(new ArrayList<String>());
			}

			Criteria<ProductBean> criteria = manager
					.generateCriteria(ProductBean.class);
			if (productCategroy != null) {
				criteria.addRestriction(ProductBean.COL_PRODUCT_CATEGORY_ID,
						Operators.isEqual, productCategroy.getCategoryCode());
			}
			criteria.setOrderBy(ProductBean.COL_DESCRIPTION, true);
			productBeans = criteria.execute();
			//
			// progressDlg = new ProgressDialog(this);
			// progressDlg.setMessage("Please Wait!");
			// progressDlg.setTitle("Searching...");
			// progressDlg.setCancelable(false);
			// progressDlg.show();
			//
			// Thread thread = new Thread() {
			// public void run() {
			// try {
			// Thread.sleep(1000);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
			// handler.post(new Runnable() {
			// @Override
			// public void run() {

			buildProductTable();
			// progressDlg.dismiss();
			// }
			// });
			//
			// }
			// };
			// thread.start();

			// ((Button) findViewById(R.id.add_search_items))
			// .setOnClickListener(this);
			// ((Button) findViewById(R.id.cancel_result))
			// .setOnClickListener(this);

		} catch (Exception e) {
			logger.logException("Initializer Exception :", e);
		}

	}

	/**
	 * Build Product Table
	 */
	private void buildProductTable() {
		try {
			// myList = (ListView) findViewById(R.id.MyList);

			myAdapter = new MyAdapter(roverApp, R.layout.item,
					R.id.product_code);
			myAdapter.setSize(productBeans.size());
			// myAdapter.add(new Item("Apple", 0.99,""));
			// myAdapter.add(new Item("Orange", 1.50,""));
			// myAdapter.add(new Item("Tomato", 1.00,""));
			//

			for (ProductBean productBean : productBeans) {
				productitem.add(new Item(productBean.getDescription(),
						productBean.getUnitPrice(), ""));
				myAdapter.add(new Item(productBean.getDescription(),
						productBean.getUnitPrice(), ""));
			}

			setListAdapter(myAdapter);

			getListView().setTextFilterEnabled(true);

		} catch (Exception e) {
			logger.logException("buildProductTable Exception ", e);
		}
	}

	//
	// @Override
	// public void onClick(View view) {
	// try {
	//
	// switch (view.getId()) {
	// case R.id.add_search_items:
	// addSearchItems();
	// break;
	// case R.id.cancel_result:
	// this.finish();
	// break;
	//
	// default:
	// break;
	// }
	// } catch (Exception e) {
	// logger.logException("onClick Exception ", e);
	// }
	//
	// }

	private void addSearchItems() {
		try {

			TableLayout productsTable = (TableLayout) findViewById(R.id.search_result_dlg);
			int count = productsTable.getChildCount();
			TableRow row;
			String quantity;

			ProductBean productBean;

			List<ProductBean> productBeanList = new ArrayList<ProductBean>();
			List<String> productBeanQuantityList = new ArrayList<String>();

			for (int i = 1; i < count; i++) {
				row = (TableRow) productsTable.getChildAt(i);
				quantity = ((EditText) row.getChildAt(2)).getText().toString()
						.trim();
				if (!quantity.equals("")) {
					productBean = (ProductBean) row.getTag();
					productBeanList.add(productBean);
					productBeanQuantityList.add(quantity);

				}
			}

			roverApp.getViewContext().put(
					RoverConstants.CURRENT_ORDER_PRODUCT_LIST, productBeanList);
			roverApp.getViewContext().put(
					RoverConstants.CURRENT_ORDER_QUANTITY_LIST,
					productBeanQuantityList);
			setResult(RoverConstants.CURRENT_ORDER_SUCESS);
			this.finish();
		} catch (Exception e) {
			logger.logException("addSearch Items", e);
		}
	}

	public class MyAdapter extends ArrayAdapter<Item> {

		public String[] productQuantity;

		public MyAdapter(Context context, int textViewResourceId, int id) {
			super(context, textViewResourceId, id);

		}

		public void setSize(int size) {
			productQuantity = new String[size];
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder viewHolder = null;

			if (convertView == null) {
				viewHolder = new ViewHolder();
				LayoutInflater mInflater = (LayoutInflater) getContext()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				convertView = mInflater.inflate(R.layout.item, null);
				viewHolder.productCode = ((TextView) convertView
						.findViewById(R.id.product_code));
				viewHolder.productPrice = ((TextView) convertView
						.findViewById(R.id.product_price));
				viewHolder.quantity = ((EditText) convertView
						.findViewById(R.id.product_input));
				viewHolder.quantityValue = "";
				
				convertView.setTag(viewHolder);

			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			Item productBean = getItem(position);

			viewHolder.productCode.setText(productBean.getName());
			viewHolder.productPrice.setText(productBean.getPrice());
			if (viewHolder.quantityValue != "")
				viewHolder.quantity.setText(viewHolder.quantityValue);
			viewHolder.quantity.setId(position);

			// Fill EditText with the value you have in data source

			viewHolder.productCode.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					v.setFocusableInTouchMode(true);
					v.requestFocus();

				}
			});

			// we need to update adapter once we finish with editing
			viewHolder.quantity
					.setOnFocusChangeListener(new OnFocusChangeListener() {
						public void onFocusChange(View v, boolean hasFocus) {
							if (!hasFocus) {
								final int position = v.getId();
								final EditText quantity = (EditText) v;
								
								View view=((View)v.getParent());
								((ViewHolder)view.getTag()).quantityValue = quantity.getText()
										.toString();
							}
						}
					});

			return convertView;
		}

	}
}
